/*
This Tutorial shows how to load a Quake 3 map into the
engine, create a SceneNode for optimizing the speed of
rendering and how to create a user controlled camera.

Lets start like the HelloWorld example: We include
the irrlicht header files and an additional file to be able
to ask the user for a driver type using the console.
*/
#include <irrlicht.h>
#include <iostream>

#include "RTSCamera.h"
#include "EventCatcher.h"
#include "Handlers/KeyHandler.h"


using namespace irr;
using namespace scene;

float distance;
const float SPEED = 10.0f;

/*
Again, to be able to use the Irrlicht.DLL file, we need to link with the 
Irrlicht.lib. We could set this option in the project settings, but
to make it easy, we use a pragma comment lib:
*/
//#pragma comment(lib, "Irrlicht.lib")


//! produces a serie of screenshots
/*class CScreenShotFactory : public IEventReceiver
{
public:

	CScreenShotFactory( IrrlichtDevice *device, const c8 * templateName )
	{
		// store pointer to device so we can use it
		Device = device;

		// start with zero
		Number = 0;

		Filename.reserve ( 256 );
		FilenameTemplate = templateName;
	}

	bool OnEvent(const SEvent& event)
	{
		// check if user presses the key F9
		if (event.EventType == EET_KEY_INPUT_EVENT &&
			event.KeyInput.Key == KEY_F9 &&
			event.KeyInput.PressedDown == false)
		{
			video::IImage* image = Device->getVideoDriver()->createScreenShot();
			if (image)
			{
				sprintf (	(c8*) Filename.c_str() ,
							"%s_shot%04d.jpg",
							FilenameTemplate.c_str (),
							Number++
						);
				Device->getVideoDriver()->writeImageToFile(image, Filename.c_str(), 85 );
				image->drop();
			}
		}
		return false;
	}

private:
	IrrlichtDevice *Device;
	u32 Number;
	core::stringc Filename;
	core::stringc FilenameTemplate;
};
*/

/*
Ok, lets start. 
*/

int IRRCALLCONV main(int argc, char* argv[])
{
	/*
	Like in the HelloWorld example, we create an IrrlichtDevice with
	createDevice(). The difference now is that we ask the user to select 
	which hardware accelerated driver to use. The Software device would be
	too slow to draw a huge Quake 3 map, but just for the fun of it, we make
	this decision possible too.
	*/

//	// ask user for driver
//
	video::E_DRIVER_TYPE driverType;
//
//	printf("Please select the driver you want for this example:\n"\
//		" (a) Direct3D 9.0c\n (b) Direct3D 8.1\n (c) OpenGL 1.5\n"\
//		" (d) Software Renderer\n (e) Burning's Software Renderer\n"\
//		" (f) NullDevice\n (otherKey) exit\n\n");
//
//	char i;
//	std::cin >> i;
//
//	switch(i)
//	{
//		case 'a': driverType = video::EDT_DIRECT3D9;break;
//		case 'b': driverType = video::EDT_DIRECT3D8;break;
//		case 'c': driverType = video::EDT_OPENGL;   break;
//		case 'd': driverType = video::EDT_SOFTWARE; break;
//		case 'e': driverType = video::EDT_BURNINGSVIDEO;break;
//		case 'f': driverType = video::EDT_NULL;     break;
//		default: return 1;
//	}	
	
	driverType = video::EDT_OPENGL;

	// create device and exit if creation failed
	core::dimension2di videoDim ( 1024,600 );

	IrrlichtDevice *device = createDevice(driverType, videoDim, 32, false );

	if (device == 0)
		return 1; // could not create selected driver.


	/*
	Get a pointer to the video driver and the SceneManager so that
	we do not always have to write device->getVideoDriver() and
	device->getSceneManager().
	*/
	video::IVideoDriver* driver = device->getVideoDriver();
	scene::ISceneManager* smgr = device->getSceneManager();

	//! add our private media directory to the file system
	device->getFileSystem()->addFolderFileArchive("../../media/");
	device->getFileSystem()->addFolderFileArchive("tekkblade/");

	IAnimatedMesh* tekMesh = smgr->getMesh("tekkblade/tris.md2");
	IAnimatedMeshSceneNode* tekNode = smgr->addAnimatedMeshSceneNode( tekMesh );	
	tekNode->setMaterialTexture(0, driver->getTexture("tekkblade/blade.pcx"));
	tekNode->setMaterialFlag(video::EMF_LIGHTING, false); // enable dynamic lighting

	IAnimatedMesh* marineMesh[30];
	IAnimatedMeshSceneNode* marineNode[30];
	for(int zzz = 0; zzz < 30; zzz++) {
		marineMesh[zzz] = smgr->getMesh("barret/tris.md2");
		marineNode[zzz] = smgr->addAnimatedMeshSceneNode( marineMesh[zzz] );	
		marineNode[zzz]->setMaterialTexture(0, driver->getTexture("barret/barret.pcx"));
		marineNode[zzz]->setMaterialFlag(video::EMF_LIGHTING, false); // enable dynamic lighting
	}
	//tekNode->getMaterial(0).Shininess = 20.0f; // set size of specular highlights
	
	
	/*
	To display the Quake 3 map, we first need to load it. Quake 3 maps
	are packed into .pk3 files wich are nothing other than .zip files.
	So we add the .pk3 file to our FileSystem. After it was added,
	we are able to read from the files in that archive as they would
	directly be stored on disk.
	*/
	device->getFileSystem()->addZipFileArchive("../../media/map-20kdm2.pk3");
	//device->getFileSystem()->addFolderFileArchive("/baseq3/");
	
	/* 
	Now we can load the mesh by calling getMesh(). We get a pointer returned
	to a IAnimatedMesh. As you know, Quake 3 maps are not really animated,
	they are only a huge chunk of static geometry with some materials
	attached. Hence the IAnimated mesh consists of only one frame,
	so we get the "first frame" of the "animation", which is our quake level
	and create an OctTree scene node with it, using addOctTreeSceneNode().
	The OctTree optimizes the scene a little bit, trying to draw only geometry
	which is currently visible. An alternative to the OctTree would be a 
	AnimatedMeshSceneNode, which would draw always the complete geometry of 
	the mesh, without optimization. Try it out: Write addAnimatedMeshSceneNode
	instead of addOctTreeSceneNode and compare the primitives drawed by the
	video driver. (There is a getPrimitiveCountDrawed() method in the 
	IVideoDriver class). Note that this optimization with the Octree is only
	useful when drawing huge meshes consisting of lots of geometry.
	*/
	scene::IQ3LevelMesh* mesh = (scene::IQ3LevelMesh*) smgr->getMesh("maps/20kdm2.bsp");
	//scene::IQ3LevelMesh* mesh = (scene::IQ3LevelMesh*) smgr->getMesh("maps/q3dm14.bsp");

	// create an event receiver for making screenshots
	EventCatcher myCatcher = EventCatcher(device);
	boost::shared_ptr<EventHandler> tempPtr(new KeyHandler);
	myCatcher.RegisterEventHandler(tempPtr);
	device->setEventReceiver ( &myCatcher );


	/*
		add the geometry mesh to the Scene ( polygon & patches )
		The Geometry mesh is optimised for faster drawing
	*/
	scene::ISceneNode* node = 0;
	if ( mesh )
	{
		scene::IMesh* geometry = mesh->getMesh(quake3::E_Q3_MESH_GEOMETRY );
		//geometry->setMaterialFlag(video::EMF_WIREFRAME,true);
		node = smgr->addMeshSceneNode ( geometry );
	}

	/*
		now construct SceneNodes for each Shader
		The Objects are stored in the quake mesh scene::E_Q3_MESH_ITEMS
		and the Shader ID is stored in the MaterialParameters
		mostly dark looking skulls and moving lava.. or green flashing tubes?
	*/
	if ( mesh )
	{
		// the additional mesh can be quite huge and is unoptimized
		scene::IMesh * additional_mesh = mesh->getMesh ( quake3::E_Q3_MESH_ITEMS );

		for ( u32 i = 0; i!= additional_mesh->getMeshBufferCount (); ++i )
		{
			IMeshBuffer *meshBuffer = additional_mesh->getMeshBuffer ( i );
			const video::SMaterial &material = meshBuffer->getMaterial();

			//! The ShaderIndex is stored in the material parameter
			s32 shaderIndex = (s32) material.MaterialTypeParam2;

			// the meshbuffer can be rendered without additional support, or it has no shader
			const quake3::SShader *shader = mesh->getShader ( shaderIndex );
			if ( 0 == shader )
			{
				continue;
			}

			// we can dump the shader to the console in it's original but already parsed layout
			// in a pretty printers way.. commented out, because the console would be full...
			// quake3::dumpShader ( Shader );

			// Now add the MeshBuffer(s) with the current Shader to the Manager
			smgr->addQuake3SceneNode ( meshBuffer, shader );
		}

		// original mesh is not needed anymore
		mesh->releaseMesh ( quake3::E_Q3_MESH_ITEMS );
	}

	/*
		Now we only need a Camera to look at the Quake 3 map.
		And we want to create a user controlled camera. There are some
		different cameras available in the Irrlicht engine. For example the 
		Maya Camera which can be controlled compareable to the camera in Maya:
		Rotate with left mouse button pressed, Zoom with both buttons pressed,
		translate with right mouse button pressed. This could be created with
		addCameraSceneNodeMaya(). But for this example, we want to create a 
		camera which behaves like the ones in first person shooter games (FPS).
	*/
	
    scene::ICameraSceneNode* camera = smgr->addCameraSceneNodeFPS();
	//scene::ICameraSceneNode* camera = smgr->addCameraSceneNodeMaya();
	
//	RTSCamera* camera = new RTSCamera(device,smgr->getRootSceneNode(),smgr,-1,1000.0f,10.0f,10.0f);
	/*
		so we need a good starting Position in the level.
		we can ask the Quake3 Loader for all entities with class_name "info_player_deathmatch"
		we choose a random launch
		
	*/
	
	/*
	The mouse cursor needs not to be visible, so we make it invisible.
	*/

	//device->getCursorControl()->setVisible(false);
//	device->getCursorControl()->grab();

	// load the engine logo
	gui::IGUIEnvironment* env = device->getGUIEnvironment();
	env->addImage(driver->getTexture("irrlichtlogo2.png"),core::position2d<s32>(10, 10));

	// show the driver logo
	core::position2di pos ( videoDim.Width - 128, videoDim.Height - 64 );

	switch ( driverType )
	{
		case video::EDT_BURNINGSVIDEO:
			env->addImage(driver->getTexture("burninglogo.png"),pos );
			break;
		case video::EDT_OPENGL:
			env->addImage(driver->getTexture("opengllogo.png"),pos );
			break;
		case video::EDT_DIRECT3D8:
		case video::EDT_DIRECT3D9:
			env->addImage(driver->getTexture("directxlogo.png"),pos );
			break;
	}

	/*
	We have done everything, so lets draw it. We also write the current
	frames per second and the drawn primitives to the caption of the
	window. The 'if (device->isWindowActive())' line is optional, but 
	prevents the engine render to set the position of the mouse cursor 
	after task switching when other program are active.
	*/
	int lastFPS = -1;

	long int ztimer = 0;
	
	tekNode->setPosition(core::vector3df(camera->getPosition().X+40.0f+float(ztimer/10.0f),camera->getPosition().Y+40.0f,camera->getPosition().Z));
	for(int zzz = 0; zzz < 6; zzz++) {
		for(int yyy = 0; yyy < 5; yyy++) {
			marineNode[zzz+yyy*6]->setPosition(core::vector3df(camera->getPosition().X+(30.0f*zzz)+float(ztimer/10.0f),camera->getPosition().Y+20.0f,camera->getPosition().Z+20.0f*yyy));
		}
	}

	distance = 15000.0f;
	
	scene::ISceneNodeAnimator* animator;
	animator = smgr->createFlyStraightAnimator(tekNode->getPosition(),core::vector3df(tekNode->getPosition().X+distance,tekNode->getPosition().Y,tekNode->getPosition().Z),distance*SPEED,false);
	tekNode->addAnimator(animator);
	animator->drop();
	tekNode->setFrameLoop(160, 183);
	tekNode->setAnimationSpeed(40);
	tekNode->setMD2Animation(scene::EMAT_RUN);
	scene::ISceneNodeAnimator* animatorMarine[30];
	for(int zzz = 0; zzz < 30; zzz++) {
		animatorMarine[zzz] = smgr->createFlyStraightAnimator(marineNode[zzz]->getPosition(),core::vector3df(marineNode[zzz]->getPosition().X+distance,marineNode[zzz]->getPosition().Y,marineNode[zzz]->getPosition().Z),distance*SPEED,false);
		marineNode[zzz]->addAnimator(animatorMarine[zzz]);
		animatorMarine[zzz]->drop();
        marineNode[zzz]->setFrameLoop(160, 183);
        marineNode[zzz]->setAnimationSpeed(40);
        marineNode[zzz]->setMD2Animation(scene::EMAT_RUN);
	}

	while(device->run())
	if (device->isWindowActive())
	{
		//camera->getRotation()
		driver->beginScene(true, true, video::SColor(255,20,20,40));
		smgr->drawAll();
		env->drawAll();
		
		driver->endScene();

		int fps = driver->getFPS();

		//if (lastFPS != fps)
		{
			io::IAttributes * attr = smgr->getParameters();

			s32 calls = attr->getAttributeAsInt ( "calls" );
			s32 culled = attr->getAttributeAsInt ( "culled" );

			core::stringw str = L"Q3 [";
			str += driver->getName();
			str += "] FPS:";
			str += fps;
			str += " Cull:";
			str += calls;
			str += "/";
			str += culled;

			device->setWindowCaption(str.c_str());
			lastFPS = fps;
		}
	}

	/*
	In the end, delete the Irrlicht device.
	*/
	device->drop();
	
	return 0;
}


